<template>
  <div>
    <el-upload
      :action="CMBASE.baseUploadAction"
      accept="image/jpeg,image/gif,image/png"
      :limit="limit"
      :on-exceed="uploadOverRun"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-preview="handlePictureCardPreview"
      :on-error="handleError"
      :file-list="fileLists"
      multiple
      list-type="picture-card"
      class="app-uploader"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog
      :visible.sync="dialogVisible"
      width="33%"
    >
      <img style="width: 100%;height: 100%;object-fit: contain" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  props: {
    value: {
      type: String
    },
    limit: {
      type: Number,
      default: 1
    },
    fileList: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileLists: [],
      dialogImageUrl: '',
      dialogVisible: false,
      images: []
    }
  },
  watch: {
    fileList: {
      handler(newVal, oldVal) {
        if (newVal !== '' && newVal !== undefined) {
          const arr = []
          newVal.split(',').forEach(item => {
            arr.push({
              url: this.CMBASE.baseFileContext + item
            })
          })
          this.fileLists = arr
        }
      },
      immediate: true,
      deep: true
    },
    value: {
      handler(newVal, oldName) {
        if (newVal !== '' && newVal !== undefined) {
          this.images = newVal.split(',')
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {

  },
  methods: {
    /* 多图上传预览 */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /* 多图上传限制 */
    uploadOverRun() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    /* 多图上传移除 */
    handleRemove(file) {
      for (var i = 0; i < this.images.length; i++) {
        // 存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        let url
        // 后台已有照片
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.path
        }
        if (url.includes(this.images[i])) {
          this.images.splice(i, 1)
        }
      }
      this.$emit('input', this.images.toString())
    },
    // 上传错误时的钩子
    handleError() {
      this.$message({ message: '上传失败', type: 'error' })
    },
    /* 文件上传成功 */
    handleSuccess(res) {
      if (res.state === 'success') {
        this.images.push(res.path)
        this.$emit('input', this.images.toString())
      } else {
        this.$message.error(res.msg + '上传失败请稍后重试！')
      }
    }
  }
}
</script>
<style>
  .el-upload-list{
    display: inline-grid;
  }
</style>
